'''
Created on Apr 12, 2012

@author: dolphinigle
'''
import unittest
import util
import fractions

class Test(unittest.TestCase):

  def testToBits(self):
    self.assertEquals([0, 1, 0, 1, 1], util.ToBits(11, 5))
    self.assertEquals([0], util.ToBits(0, 1))
    self.assertEquals([0, 0, 0, 0, 0], util.ToBits(0, 5))
    self.assertEquals([1, 1, 1, 1], util.ToBits(15, 4))
    
  def testFromBitToInt(self):
    self.assertEquals(11, util.FromBitToInt([0, 1, 0, 1, 1]))
    self.assertEquals(0, util.FromBitToInt([0]))
    self.assertEquals(15, util.FromBitToInt([1, 1, 1, 1]))
  
  def testLeftRotate(self):
    self.assertEquals(22, util.BitLeftRotate(5, 11))
    self.assertEquals(0, util.BitLeftRotate(1, 0))
    self.assertEquals(7, util.BitLeftRotate(4, 11))
  
  def testMultiLeftRotate(self):
    self.assertEquals(14, util.MultiLeftRotate(4, 11, 2))
  
  def testToHex(self):
    self.assertEquals(4, len(util.ToHex(16, 3227)))
    self.assertEquals(5, len(util.ToHex(20, 1234)))
  
  def testHexToInt(self):
    self.assertEquals(12375, util.HexToInt(util.ToHex(32, 12375)))
    self.assertEquals(1237123129381942341235,
                      util.HexToInt(util.ToHex(100, 1237123129381942341235)))
  
  def testModExp(self):
    self.assertEquals(8, util.ModExp(2, 3, 10))
    self.assertEquals(12, util.ModExp(3, 3, 15))
  
  def testExtendedEuclid(self):
    for i in range(-220, 220):
      for j in range(-220, 220):
        if not i or not j:
          continue
        gc = abs(fractions.gcd(i, j))
        (a, b) = util.ExtendedEuclid(i, j)
        self.assertEquals(gc, a * i + b * j)
  
  def testModInverse(self):
    for i in range(1, 220):
      for j in range(1, 220):
        if i < j and fractions.gcd(i, j) == 1:
          self.assertEquals(1, (i * util.ModInverse(i, j)) % j)

if __name__ == "__main__":
  #import sys;sys.argv = ['', 'Test.testToBits']
  unittest.main()